package com.groupbuying.orderconsumer.service.impl;

import com.alibaba.fastjson.JSON;
import com.groupbuying.orderconsumer.connector.JGFeign;
import com.groupbuying.orderconsumer.connector.PayFeign;
import com.groupbuying.orderconsumer.connector.StoreFeign;
import com.groupbuying.orderconsumer.connector.SysConfigFeign;
import com.groupbuying.orderconsumer.constant.CommonConstants;
import com.groupbuying.orderconsumer.constant.OrderUshopEnumConstants;
import com.groupbuying.orderconsumer.dao.OrderUshopDao;
import com.groupbuying.orderconsumer.domain.OrderUshopDO;
import com.groupbuying.orderconsumer.service.OrderUshopService;
import com.groupbuying.orderconsumer.utils.DateUtils;
import com.groupbuying.orderconsumer.utils.HttpClientUtils;
import com.groupbuying.orderconsumer.utils.RedisUtils;
import com.groupbuying.orderconsumer.utils.WeiXinUtils;
import com.groupbuying.orderconsumer.utils.apiresult.ApiResult;
import com.groupbuying.orderconsumer.utils.apiresult.ApiResultCode;
import com.groupbuying.orderconsumer.webSocket.WebSocketServer;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class OrderUshopServiceImpl implements OrderUshopService {
    private static Logger log = LoggerFactory.getLogger(OrderUshopServiceImpl.class);
    @Autowired
    private WeiXinUtils weiXinUtils;
    @Autowired
    private StoreFeign storeFeign;
    @Autowired
    private PayFeign payFeign;
    @Autowired
    private HttpClientUtils httpClientUtils;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private OrderUshopDao orderUshopDao;

    @Autowired
    private SysConfigFeign sysConfigFeign;

    @Autowired
    private JGFeign jgFeign;


    @Override
    public OrderUshopDO get(String orderId) {
        return orderUshopDao.get(orderId);
    }

    @Override
    public List<OrderUshopDO> list(Map<String, Object> map) {
        return orderUshopDao.list(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        return orderUshopDao.count(map);
    }

    @Override
    public int save(OrderUshopDO orderUshop) {
        return orderUshopDao.save(orderUshop);
    }

    @Override
    public int update(OrderUshopDO orderUshop) {
        return orderUshopDao.update(orderUshop);
    }

    @Override
    public int remove(String orderId) {
        return orderUshopDao.remove(orderId);
    }

    @Override
    public int batchRemove(String[] orderIds) {
        return orderUshopDao.batchRemove(orderIds);
    }


    /**
     * 修改交易状态
     *
     * @param orderId   订单ID
     * @param dealState 交易状态
     * @return
     */
    @Override
    public ApiResult updateDealState(String orderId, String dealState) {
        if (StringUtils.isEmpty(orderId) && StringUtils.isEmpty(dealState)) {
            return ApiResult.failure("参数不能为空");
        }
        OrderUshopDO orderUshopDO = orderUshopDao.get(orderId);
        //数据库存在数据
        if (orderUshopDO != null) {
            if (dealState.equals(OrderUshopEnumConstants.ENUM_DEALSTATE_UNCLOSED) &&
                    !OrderUshopEnumConstants.ENUM_ORDERSTATE_UNPAY.equals(orderUshopDO.getOrderState())) {
                //订单完成
                orderUshopDO.setStateNote(OrderUshopEnumConstants.ENUM_STATENOTE_FINISH);
            }
            orderUshopDO.setGmtModified(new Date());
            orderUshopDO.setDealState(dealState);
            this.update(orderUshopDO);
            return ApiResult.success();
        }
        return ApiResult.failure("订单不存在");
    }

    /**
     * 关闭订单
     *
     * @param orderId   订单ID
     * @param closeType 关闭操作类型
     * @return
     */
    @Override
    public ApiResult closeDealState(String orderId, String closeType) {
        if (StringUtils.isEmpty(orderId)) {
            return ApiResult.failure("参数为空");
        }
        OrderUshopDO orderUshopDO = orderUshopDao.get(orderId);
        //存在数据且订单状态为未支付，交易状态不是已关闭
        if (orderUshopDO != null) {
            if (OrderUshopEnumConstants.ENUM_ORDERSTATE_UNPAY.equals(orderUshopDO.getOrderState()) &&
                    !OrderUshopEnumConstants.ENUM_DEALSTATE_CLOSED.equals(orderUshopDO.getDealState())) {
                if (CommonConstants.AUTO_OPERATION.equals(closeType)) {
                    orderUshopDO.setDealState(OrderUshopEnumConstants.ENUM_DEALSTATE_CLOSED);
                    orderUshopDO.setStateNote(OrderUshopEnumConstants.ENUM_STATENOTE_TIMEOUT);
                    //TODO 支付中心查询支付状态是否有支付完成的情况
                } else if (CommonConstants.USER_OPERATION.equals(closeType)) {
                    orderUshopDO.setDealState(OrderUshopEnumConstants.ENUM_DEALSTATE_CLOSED);
                    orderUshopDO.setStateNote(OrderUshopEnumConstants.ENUM_STATENOTE_CANCEL);
                }
                orderUshopDO.setGmtModified(new Date());
                this.update(orderUshopDO);
            }

            return ApiResult.success();
        }
        return ApiResult.failure("订单不存在");
    }

    /**
     * 修改订单状态
     *
     * @param orderId    订单id
     * @param orderState 订单状态
     * @return
     */
    @Override
    public ApiResult updateOrderState(String orderId, String orderState) {
        if (StringUtils.isEmpty(orderId) && StringUtils.isEmpty(orderState)) {
            return ApiResult.failure("参数不能为空");
        }
        try {
            //redis加锁防止重复消费
            if (orderState.equals(OrderUshopEnumConstants.ENUM_ORDERSTATE_PAY) && redisUtils.isHasKey(CommonConstants.REDIS_SIGN + orderId)) {
                return new ApiResult(ApiResultCode.METHOD_ON_THE_WAY.code(), ApiResultCode.METHOD_ON_THE_WAY.message());
            } else if (orderState.equals(OrderUshopEnumConstants.ENUM_ORDERSTATE_PAY) && !redisUtils.isHasKey(CommonConstants.REDIS_SIGN + orderId)) {
                redisUtils.setKey(CommonConstants.REDIS_SIGN + orderId, orderId, CommonConstants.EXPIRE_TIME);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("redis出错：{}", e.getMessage());
        }

        OrderUshopDO orderUshopDO = orderUshopDao.get(orderId);
        //数据库存在数据且交易状态为进行中
        if (orderUshopDO != null ) {
            //如果修改订单状态为退款成功
            if (OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDED.equals(orderState)) {
                //修改交易状态为关闭，并修改状态备注为退款完成交易关闭
                orderUshopDO.setDealState(OrderUshopEnumConstants.ENUM_DEALSTATE_CLOSED);
                orderUshopDO.setStateNote(OrderUshopEnumConstants.ENUM_STATENOTE_RETURN);
            }
            orderUshopDO.setGmtModified(new Date());
            orderUshopDO.setOrderState(orderState);
            this.update(orderUshopDO);
            //判断是否是优店订单
            boolean typeNotify = orderUshopDO.getOrderId().substring(4, 7).equals("000");
            String notifyMessage = "";
            if (typeNotify) {
                notifyMessage = "优店收款到账,";
            } else {
                notifyMessage = "优惠买单收款到账,";
            }
            //支付完成的情况下：主动下发订单
            if (orderState.equals(OrderUshopEnumConstants.ENUM_ORDERSTATE_PAY)) {
                String message = notifyMessage + orderUshopDO.getOrderPrice().toString() + ",元";
                WebSocketServer.sendInfo(message, orderUshopDO.getCounterId());
                sendMessageForWXGZH(orderUshopDO);

                //推送订单信息到极光服务
                try {
                    if (StringUtils.isEmpty(orderUshopDO.getCounterId())) {
                        log.error("订单中心,修改订单状态,订单id:{},错误提示:counterId为空",orderId);
                        throw new RuntimeException("订单id不能为空");
                    }

                    //获取商户id
                    Map<String,Object> findStoreIdParam = new HashMap<>();
                    findStoreIdParam.put("counterId",orderUshopDO.getCounterId());

                    Map<String,String> storeMap = storeFeign.getStoreShopByCounterId(findStoreIdParam);
                    String storeId = storeMap.get("uuid");

                    //判断storeId是否为空
                    if (StringUtils.isEmpty(storeId)) {
                        log.error("订单中心,修改订单状态,订单id:{},counterId:{},错误提示:storeIdId为空",orderId,orderUshopDO.getCounterId());
                        throw new RuntimeException("没有查询到对应的storeId");
                    }

                    ApiResult apiResult = jgFeign.orderMessagePush(storeId,message);

                    if (!apiResult.getCode().equals(ApiResultCode.SUCCESS)) {
                        log.error("订单中心,修改订单状态,订单id:{},错误提示:推送订单信息到极光服务,失败",orderId);
                        throw new RuntimeException("推送订单信息到极光服务,失败");
                    }
                } catch (Exception e) {
                    log.error("订单中心,修改订单状态,订单id:{},错误提示:推送订单信息到极光服务出现错误",orderId);
                }
            }
            return ApiResult.success();

        }
        return ApiResult.failure("订单不存在或交易被冻结");
    }

    /**
     * 向微信公众好推送消息
     */
    private void sendMessageForWXGZH(OrderUshopDO orderUshopDO) {

        Map<String, Object> storeParams = new HashMap<>();
        storeParams.put("counterId", orderUshopDO.getCounterId());
        Map<String, String> shop = storeFeign.getStoreShopByCounterId(storeParams);
        Map<String, String> payInfo = payFeign.getPayInfoByOrderId(orderUshopDO.getOrderId());
        Map<String, Set<String>> openIds = storeFeign.getOpenIds(orderUshopDO.getCounterId());
        try {
            Map<String,Object> appParams=new HashMap<>();
            appParams.put("openId", ArrayUtils.toString(openIds.get("openId")));
            appParams.put("templateId","KetoEtfONsbLdctD4vt2is-FVyaM_2QQnR6zoUBbEx4");
            appParams.put("indicate","youdianproductor");
            Map<String,Object> dataParams=new HashMap<>();
            dataParams.put("remark","点击进入商家小程序");
            dataParams.put("keyword1",orderUshopDO.getOrderId());
            if ("3".equals(payInfo.get("payType"))) {
                dataParams.put("keyword2", payInfo.get("payCur") + "元");
            }else if ("4".equals(payInfo.get("payType"))){
                dataParams.put("keyword2", payInfo.get("payBalance") + "元");
            }else{
                dataParams.put("keyword2", payInfo.get("payMoney") + "元");
            }
            dataParams.put("keyword3",shop.get("storename"));
            dataParams.put("keyword4",DateUtils.format(orderUshopDO.getGmtModified(), DateUtils.YMDHMS));
            dataParams.put("remark","点击进入商家小程序");
            appParams.put("data",JSON.toJSON(dataParams));
            log.info("装配消息为:{}",appParams);
            ApiResult apiResult = sysConfigFeign.doWechatAppTemplateSend(appParams);
            if(ApiResultCode.SUCCESS.code().equals(apiResult.getCode())){
                log.info("微信公众号消息发布成功");
            }else{
                log.info("微信公众号消息发布失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("发送公众号出现错误 订单ID{},收银台ID:{}", orderUshopDO.getOrderId(), orderUshopDO.getCounterId());
        }

    }






}
